package main

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"net"
	"time"
)

var host = new(Host)

//主机结构体
type Host struct {
	Id             int
	Ip             string         `json:"ip"`
	LastCheck      sql.NullString `json:"last_check"`
	UpdateInterval int
	Services       []*Service
}

//服务结构体
type Service struct {
	Id             int
	Name           string
	Plugin         string
	Args           string
	UpdateInterval int
	LastCheck      time.Time
	Items          []*Item
}

//监控项结构体
type Item struct {
	Name   string
	Key    string
	Status bool
}

//连接服务端,成功返回连接句柄，失败返回nil和错误信息
func ConnectServer(ip, port string) (*net.TCPConn, error) {
	var (
		err  error
		conn *net.TCPConn
	)
	tcpAddr, _ := net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:%s", ip, port))
	conn, err = net.DialTCP("tcp", nil, tcpAddr)
	if nil == err {
		conn.SetKeepAlive(true)
		return conn, nil
	}
	return nil, err
}

//从服务端获取配置,成功更新全部变量host，失败返回错误信息
func PullConfig() {
	conn, err := ConnectServer(server, "8888")
	if err != nil {
		log.Error("can not connect to server")
		return
	}
	defer conn.Close()
	log.Info("update monitor config")
	s := map[string]interface{}{"type": "0"}
	data, _ := json.Marshal(s)
	err = SendData(conn, data)
	if err != nil {
		log.Error("pull monitor config error")
		return
	}
	res := ReadData(conn)
	err = json.Unmarshal(res, &host)
	if err != nil {
		log.Error("unmarshal config to host error <%v>", err)
		return
	}
	log.Info("update success")
}
